package com.jgit;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * 索引（暂存区）：跟踪已添加到暂存区的文件
 */
public class Index {
    private String gitDir;
    private Map<String, IndexEntry> entries;
    
    public Index(String gitDir) {
        this.gitDir = gitDir;
        this.entries = new HashMap<>();
        load();
    }
    
    /**
     * 从文件加载索引
     */
    private void load() {
        Path indexFile = Paths.get(gitDir, "index");
        if (Files.exists(indexFile)) {
            try (ObjectInputStream ois = new ObjectInputStream(
                    new FileInputStream(indexFile.toFile()))) {
                @SuppressWarnings("unchecked")
                Map<String, IndexEntry> loaded = (Map<String, IndexEntry>) ois.readObject();
                entries = loaded;
            } catch (Exception e) {
                // 如果读取失败，使用空索引
                entries = new HashMap<>();
            }
        }
    }
    
    /**
     * 保存索引到文件
     */
    public void save() throws IOException {
        Path indexFile = Paths.get(gitDir, "index");
        Files.createDirectories(indexFile.getParent());
        
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(indexFile.toFile()))) {
            oos.writeObject(entries);
        }
    }
    
    /**
     * 添加文件到索引
     */
    public void add(String path, String hash, String mode) {
        entries.put(path, new IndexEntry(path, hash, mode));
    }
    
    /**
     * 从索引中移除文件
     */
    public void remove(String path) {
        entries.remove(path);
    }
    
    /**
     * 获取所有索引条目
     */
    public Map<String, IndexEntry> getEntries() {
        return entries;
    }
    
    /**
     * 清空索引
     */
    public void clear() {
        entries.clear();
    }
    
    /**
     * 索引条目
     */
    public static class IndexEntry implements Serializable {
        private String path;
        private String hash;
        private String mode;
        
        public IndexEntry(String path, String hash, String mode) {
            this.path = path;
            this.hash = hash;
            this.mode = mode;
        }
        
        public String getPath() {
            return path;
        }
        
        public String getHash() {
            return hash;
        }
        
        public String getMode() {
            return mode;
        }
    }
}

